package com.example.onlinemarket.service;

import com.example.onlinemarket.bean.mobile.MobileOrderInfo;
import com.example.onlinemarket.dao.GoodDao;
import com.example.onlinemarket.dao.OrderDao;
import com.example.onlinemarket.dao.OrderItemDao;
import com.example.onlinemarket.dao.UserDao;
import com.example.onlinemarket.bean.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    private GoodDao goodDao;
    private OrderDao orderDao;
    private OrderItemDao orderItemDao;
    private UserDao userDao;
    @Autowired
    public void setGoodDao(GoodDao goodDao) { this.goodDao = goodDao; }
    @Autowired
    public void setUserDao(UserDao userDao) { this.userDao = userDao; }
    @Autowired
    public void setOrderItemDao(OrderItemDao orderItemDao) { this.orderItemDao = orderItemDao; }
    @Autowired
    public void setOrderDao(OrderDao orderDao){
        this.orderDao = orderDao;
    }

    public List<Order> getOrdersByUserId(Integer userId, String status) {
        return orderDao.getOrdersByUserId(userId, status);
    }

    //创建新订单并返回
    public Order addOrder(int userId, int shopId, String shopName) {
        orderDao.addOrder(userId, new Date(), shopId, shopName);
        return orderDao.getOrder(userId, shopId);
    }

    //将鲜花添加到购物车，若现有购物车订单中有该商家对应订单则添加到该订单，若无则创建新订单
    public void addShoppingCart(int userId, int goodId){
        Order order = getUserShoppingOrder(userId, goodId);
        List<OrderItem> orderItems = orderItemDao.getOrderItemsByOrderId(order.getOrderId());
        boolean isGoodExists = false;
        for(OrderItem item:orderItems){
            if(item.getGoodId()==goodId){
                orderItemDao.updateGoodNum(order.getOrderId(), goodId, item.getGoodNUm()+1);
                isGoodExists = true;
                break;
            }
        }
        if(!isGoodExists)
            orderItemDao.addOrderItem(order.getOrderId(), goodId, 1);
    }

    //获取用户购物车的订单ID
    public Order getUserShoppingOrder(int userId, int goodId) {
        Order userOrder = null;
        List<Order> orders = getOrdersByUserId(userId, "购物车");
        int shopId = goodDao.getShopIdByGoodId(goodId);
        String shopName = userDao.getUserNameById(shopId);
        //若用户无购物车则新建购物车
        if (orders.isEmpty()){
            userOrder = addOrder(userId, shopId, shopName);
        }else{//否则取得购物车
            boolean isSameOrder = false;
            for(Order order:orders){
                if(order.getShopId()==shopId) {
                    isSameOrder = true;
                    userOrder = order;
                }
            }
            if(!isSameOrder)
                userOrder = addOrder(userId, shopId, shopName);
            userOrder.setShopId(shopId);
            userOrder.setShopName(shopName);
        }
        return userOrder;
    }

    //获取用户购物车的订单ID
    public Order getUserShoppingOrder(Integer userId) {
        Order userOrder = null;
        List<Order> orders = getOrdersByUserId(userId, "购物车");
        if (!orders.isEmpty()){
            userOrder = orders.get(0);
        }
        return userOrder;
    }










    public List<Order> getShoppingOrders(int userId){
        return orderDao.getShoppingOrders(userId);
    }

    public boolean haveShoppingCart(Integer userId) {
        List<Order> orders = getOrdersByUserId(userId, "购物车");
        return !orders.isEmpty();
    }

    public boolean payment(Integer userId, Integer orderId) {
        List<OrderItem> orderItems = orderItemDao.getOrderItemsByOrderId(orderId);
        Double count = 0.0;
        for (OrderItem orderItem: orderItems) {
            count += orderItem.getGoodNUm() * goodDao.getGoodSellPriceByGoodId(orderItem.getGoodId());
        }
        return orderDao.updateOrderCount(orderId, count);
    }

    public boolean updateOrderStatus(Integer orderId, String status, String address) {
        return orderDao.updateOrderStatus(orderId, new Date(), status, address)&&
                orderItemDao.updateOrderItemStatus(orderId, status);
    }

    public Model getOrders(Model model, Integer userId, String orderStatus){
        List<OrderInfo> orderInfos = null;
        switch (orderStatus) {
            case "unSent":
                orderInfos = getUserOrder(userId, "待发货", false);
                model.addAttribute("unSentOrders", orderInfos);
                break;
            case "sent":
                orderInfos = getUserOrder(userId, "已发货", false);
                model.addAttribute("sentOrders", orderInfos);
                break;
            case "signed":
                orderInfos = getUserOrder(userId, "已签收", false);
                model.addAttribute("signedOrders", orderInfos);
                break;
            case "refund":
                orderInfos = getUserOrder(userId, "已退款", false);
                model.addAttribute("refundOrders", orderInfos);
                break;
            case "refunding":
                orderInfos = getUserOrder(userId, "%退款中", false);
                model.addAttribute("refundingOrders", orderInfos);
                break;
            case "confirm":
                orderInfos = getUserOrder(userId, "已确认", false);
                model.addAttribute("confirmOrders", orderInfos);
                break;
        }
        return model;
    }

    public List<MobileOrderInfo> getMobileOrders(int userId, String orderStatus){
        return getUserOrder(userId, orderStatus, true);
    }

    public List getUserOrder(Integer userId, String orderStatus, boolean isMobile) {
        List<Order> orders = orderDao.getUserOrdersInStatus(userId, orderStatus);
        if(isMobile){
            List<MobileOrderInfo> orderInfos = new ArrayList<>();
            for (Order order : orders) {
                MobileOrderInfo orderInfo = new MobileOrderInfo(order);
                int orderId = orderInfo.order.getOrderId();
                List<OrderItem> orderItems = orderItemDao.getOrderItemsByOrderId(orderId);
                for (OrderItem orderItem : orderItems) {
                    Good good = goodDao.getGoodById(orderItem.getGoodId());
                    orderInfo.addOrderItem(good, orderItem.getGoodNUm());
                }
                if(orderItems.size()>0){
                    Good good = goodDao.getGoodById(orderItems.get(0).getGoodId());
                    String userName = userDao.getUserNameById(good.getUserId());
                    order.setShopId(good.getUserId());
                    order.setShopName(userName);
                }// TODO: 2021/6/11  
                orderInfos.add(orderInfo);
            }
            return orderInfos;
        }else{
            List<OrderInfo> orderInfos = new ArrayList<>();
            List<User> users = new ArrayList<>();
            List<List<OrderedGood>> goods = new ArrayList<>();
            for (Order order: orders){
                List<OrderItem> orderItemList = orderItemDao.getOrderItemsByOrderId(order.getOrderId());
                List<OrderedGood> orderedGoods = new ArrayList<>();
                for (OrderItem orderItem: orderItemList) {
                    orderedGoods.add(new OrderedGood(goodDao.getGoodById(orderItem.getGoodId()), orderItem));
                }
                goods.add(orderedGoods);
                users.add(userDao.getUserById(order.getUserId()));
            }
            for(int i=0; i<orders.size(); i++){
                orderInfos.add(new OrderInfo(users.get(i), orders.get(i), goods.get(i)));
            }
            return orderInfos;
        }


    }

    public List<OrderInfo> getShopOrder(Integer userId, List<Integer> goodIds, String orderStatus) {
        List<Order> orders = orderDao.getShopOrders(userId, orderStatus);
        List<User> users = new ArrayList<>();
        List<OrderInfo> orderInfos = new ArrayList<>();
        List<List<OrderedGood>> goods = new ArrayList<>();
        for (Order order: orders){
            List<OrderItem> orderItemList = orderItemDao.getOrderItemsByOrderId(order.getOrderId());
            orderItemList.removeIf(orderItem -> !goodIds.contains(orderItem.getGoodId()));
            List<OrderedGood> orderedGoods = new ArrayList<>();
            for (OrderItem orderItem: orderItemList) {
                orderedGoods.add(new OrderedGood(goodDao.getGoodById(orderItem.getGoodId()), orderItem));
            }
            goods.add(orderedGoods);
            users.add(userDao.getUserById(order.getUserId()));
        }
        for(int i=0; i<orders.size(); i++){
            orderInfos.add(new OrderInfo(users.get(i), orders.get(i), goods.get(i)));
        }
        return orderInfos;
    }

    public Order getOrderByOrderId(Integer orderId) {
        return orderDao.getOrderByOrderId(orderId);
    }
    public boolean delOrderByOrderId(Integer orderId) {
        return orderDao.delOrderById(orderId);
    }

    //删除空订单，更新非空订单信息
    public void updateOrderInfo(int orderId, String note) {
        int count = orderItemDao.getOrderItemCount(orderId);
        if(count<=0)
            orderDao.delOrderById(orderId);
        else
            orderDao.updateOrderNote(orderId, note);
    }

    //订单退款/取消退款
    public void updateOrder(int orderId) {
        String orderStatus = orderDao.getOrderStatus(orderId);
        if(orderStatus.contains("-"))
            orderDao.updateOrder(orderId, orderStatus.split("-")[0]);
        else if(orderStatus.equals("已退款")||orderStatus.equals("已确认"))
            orderDao.delOrderById(orderId);
        else
            orderDao.updateOrder(orderId, orderStatus+"-退款中");
    }

    public void updateOrder(int orderId, String orderStatus) {
        orderDao.updateOrder(orderId, orderStatus);
    }
}
